﻿using B.S.Packaged.Domain;
using B.S.Packaged.ErrorCode;
using B.S.Packaged.WebAPI.Read.Application.Command.PackagingPlanCommands;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SqlSugar;

namespace B.S.Packaged.WebAPI.Read.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PackagingPlanController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ISqlSugarClient db;

        public PackagingPlanController(IMediator mediator, ISqlSugarClient db)
        {
            _mediator = mediator;
            this.db = db;
        }

        /// <summary>
        /// 获取包装计划表
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public async Task<APIResult<APIPaging<PackagingPlan>>> GetPackagingPlan([FromQuery] GetPackagingPlanCommands request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 根据ID查询包装计划
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public async Task<APIResult<List<PackagingPlan>>> GetBYIdPackagingPlan([FromQuery] GetBYIdPackagingPlanCommands request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 根据ID查询包装计划明细
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public async Task<APIResult<List<PackagingPlanDetails>>> GetBYIdPackagingPlanDetails([FromQuery] GetBYIdPackagingPlanDetailsCommands request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 根据ID查询物料备料信息
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public async Task<APIResult<List<Domain.MaterialPreparation>>> GetByIdMaterialPreparation([FromQuery] GetByIdMaterialPreparationCommand request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 查询计划操作记录信息
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public async Task<APIResult<APIPaging<RecordsOperations>>> GetRecordsOperations([FromQuery] GetRecordsOperationsCommand request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 导出计划方法
        /// </summary>
        /// <returns>返回任务</returns>
        [HttpGet]
        public async Task<ActionResult> ExportToExcel()
        {
            try
            {
                // 模拟查询数据，这里假设查询 User 表
                var data = db.Queryable<PackagingPlan>().OrderBy(x => x.PlannedProduction).ToList();

                // 创建一个新的 Excel 工作簿
                IWorkbook wb = new XSSFWorkbook();

                //在Excel文件中创建工作表
                ISheet sheet = wb.CreateSheet("计划表");

                //在工作表中创建行(第一行,标题);
                IRow row = sheet.CreateRow(0);

                //创建单元格
                row.CreateCell(0).SetCellValue("计划主键");
                row.CreateCell(1).SetCellValue("计划类型");
                row.CreateCell(2).SetCellValue("计划日期");
                row.CreateCell(3).SetCellValue("包装规格");
                row.CreateCell(4).SetCellValue("包装形式");
                row.CreateCell(5).SetCellValue("产品系列");
                row.CreateCell(6).SetCellValue("计划产量");
                row.CreateCell(7).SetCellValue("产量单位");
                row.CreateCell(8).SetCellValue("是否备料");
                row.CreateCell(9).SetCellValue("是否领料");
                row.CreateCell(10).SetCellValue("执行状态");
                row.CreateCell(11).SetCellValue("备注");

                var index = 1;
                foreach (var item in data)
                {
                    row = sheet.CreateRow(index);

                    row.CreateCell(0).SetCellValue(item.PackagingPlanId.ToString());
                    row.CreateCell(1).SetCellValue(item.PlanType == 1 ? "包装计划" : item.PlanType == 2 ? "过滤计划" : "其他计划");
                    row.CreateCell(2).SetCellValue(item.ScheduledDates.ToString("yyyy-MM-dd"));
                    row.CreateCell(3).SetCellValue(item.PackingSpecifications);
                    row.CreateCell(4).SetCellValue(item.PackagingForm);
                    row.CreateCell(5).SetCellValue(item.ProductRange);
                    row.CreateCell(6).SetCellValue(item.PlannedProduction.ToString());
                    row.CreateCell(7).SetCellValue(item.ProductionUnits);
                    row.CreateCell(8).SetCellValue(item.Preparation ? "已备料" : "未备料");
                    row.CreateCell(9).SetCellValue(item.Picking ? "已领料" : "未领料");
                    row.CreateCell(10).SetCellValue(item.isload == 0 ? "未执行" : item.isload == 1 ? "执行中" : "执行完毕");
                    row.CreateCell(11).SetCellValue(item.Remark);

                    index++;
                }

                //Excel的值
                byte[] buffer;
                //通过内存流读出Excel内容,转换为二进制数组
                using (MemoryStream ms = new MemoryStream())
                {
                    wb.Write(ms);
                    buffer = ms.ToArray();
                }

                //导出Excel  using  Microsoft.AspNetCore.StaticFiles;
                string excelMime = new FileExtensionContentTypeProvider().Mappings[".xlsx"];

                RecordsOperations records = new RecordsOperations();
                records.Operator = "王浩然";
                records.OperatingTime = DateTime.Now;
                records.OperationContent = "导出计划";

                await db.Insertable(records).ExecuteCommandAsync();

                //导出
                return File(buffer, excelMime, "计划表.xlsx");

            }
            catch (Exception ex)
            {
                // 处理异常
                Console.WriteLine($"导出 Excel 时出错: {ex.Message}");
            }

            return new EmptyResult();
        }
    }
}
